from flask import Blueprint, request, jsonify
from ..models import Department, Employee
from .. import db

bp = Blueprint('department', __name__, url_prefix='/api/departments')

@bp.route('/', methods=['GET'])
def get_departments():
    departments = Department.query.all()
    return jsonify([{
        'id': dept.id,
        'name': dept.name,
        'description': dept.description,
        'employee_count': Employee.query.filter_by(department_id=dept.id).count()
    } for dept in departments])

@bp.route('/<int:id>', methods=['GET'])
def get_department(id):
    department = Department.query.get_or_404(id)
    return jsonify({
        'id': department.id,
        'name': department.name,
        'description': department.description,
        'employee_count': Employee.query.filter_by(department_id=department.id).count()
    })

@bp.route('/', methods=['POST'])
def create_department():
    data = request.get_json()
    
    if not data.get('name'):
        return jsonify({'error': '部门名称不能为空'}), 400
    
    # 检查部门名称是否已存在
    if Department.query.filter_by(name=data['name']).first():
        return jsonify({'error': '部门名称已存在'}), 400
    
    department = Department(
        name=data['name'],
        description=data.get('description')
    )
    
    db.session.add(department)
    db.session.commit()
    
    return jsonify({
        'message': '部门创建成功',
        'id': department.id
    }), 201

@bp.route('/<int:id>', methods=['PUT'])
def update_department(id):
    department = Department.query.get_or_404(id)
    data = request.get_json()
    
    if 'name' in data:
        # 检查新名称是否与其他部门重复
        existing = Department.query.filter(
            Department.name == data['name'],
            Department.id != id
        ).first()
        if existing:
            return jsonify({'error': '部门名称已存在'}), 400
        department.name = data['name']
    
    if 'description' in data:
        department.description = data['description']
    
    db.session.commit()
    
    return jsonify({
        'message': '部门信息更新成功'
    })

@bp.route('/<int:id>', methods=['DELETE'])
def delete_department(id):
    department = Department.query.get_or_404(id)
    
    # 检查部门是否还有员工
    if Employee.query.filter_by(department_id=id).first():
        return jsonify({'error': '该部门下还有员工，无法删除'}), 400
    
    db.session.delete(department)
    db.session.commit()
    
    return jsonify({
        'message': '部门删除成功'
    }) 